package com.just.springmvc4.filter;
import com.sun.istack.internal.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * 拦截器，打印parameters和body日志
 */
@WebFilter(filterName = "PayloadLoggingFilter", urlPatterns = "/*",asyncSupported=true)
public class PayloadLoggingFilter implements Filter{
    private static final Logger logger= LoggerFactory.getLogger(PayloadLoggingFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //文件提交的不打印二进制内容
        if (null != request.getContentType() && request.getContentType().contains("multipart/form-data")) {
            logger.info("\n" +
                    "::::::::::::::::::::::::::Request Method: " +
                    request.getMethod() +
                    "\t" +
                    "Request URL:" +
                    request.getRequestURI() +
                    "\n");

            filterChain.doFilter(request, servletResponse);
            return;
        }
        //正戏登场
        PayloadRequestWrapper requestWrapper=new PayloadRequestWrapper(request);
        final String requestBodyRaw = nullToEmpty(requestWrapper.getBody());

        final String requestParameters = emptyToNull(
                !CollectionUtils.isEmpty(request.getParameterMap())
                        ?
                        (request.getParameterMap().entrySet().stream()
                                .map(entry -> entry.getKey() + ":" + Arrays.toString(entry.getValue()))
                                .collect(Collectors.joining(",")).trim())
                        : null);
        final String requestRaw = "\n" +
                "::::::::::::::::::::::::::[Request Method | URL]:\t" +
                request.getMethod() + " " + request.getRequestURI() +
                (!StringUtils.isEmpty(requestBodyRaw)
                        ? "\n::::::::::::::::::::::::::[Body Payload]:\n" + requestBodyRaw
                        : "") +
                (requestParameters != null
                        ? "\n::::::::::::::::::::::::::[Parameter]:\t" + requestParameters
                        : "") +
                "\n";
        logger.info(requestRaw);
        filterChain.doFilter(requestWrapper, servletResponse);
    }

    @Override
    public void destroy() {

    }

    public static String nullToEmpty(@Nullable String string) {
        return (string == null) ? "" : string;
    }

    @Nullable
    public static String emptyToNull(@Nullable String string) {
        return (string == null || string.length() == 0) ? null : string;
    }
}
